# _*_ coding: utf-8 _*_
# @Time : 2020/11/20 12:50
# @Author : moran office
# File : 桌面壁纸.py
# Software : PyChram

import requests
import json
import os
import sys

url = 'https://wallpaper.wispx.cn/api/find?rand=1'

refer = {
    "Referer": "https://wallpaper.wispx.cn/random",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
}

def get_img_url(path):
    res = requests.get(url, headers=refer)
    data = json.loads(res.text)
    # print(data['url'])
    img_url = data['url']
    # 保存下来，返回访问路径
    img_name = img_url.split('/')[-1]
    img_name = img_name.split('&')[0]
    f = open(path + img_name, 'wb')
    f.write(requests.get(img_url, headers = refer).content)
    f.close()
    return img_name

def build_path(path):
    if not os.path.exists(path):
        os.makedirs(path)

if __name__ == '__main__':
    '''
    sys.argv[1] 用于获取命令行中启动py文件传递的参数，
    因为第一个总是要运行的py文件名称，所以参数下标总是从1开始
    '''
    path = sys.argv[1]
    build_path(path)
    print(get_img_url(path))

